package com.yanqu.road.tools;

import com.yanqu.road.utils.string.StringUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;

public class ConfigUpdateOutput {
    public static void main(String[] args) {
        String needUpdateExcelStr = args[0];
        List<String> excelNames = new ArrayList<>();
        for (String s : StringUtils.stringToStringList(needUpdateExcelStr, ",")) {
            s = s + ".xlsx";
            excelNames.add(s);
        }

        String version = args[1];

        int channelId = 0;

        String dirPath = System.getProperty("user.dir") + File.separator;
        String configPath = dirPath + "config" + File.separator;
        File pathFile = new File(configPath);
        for (File file : pathFile.listFiles()) {
            if (file.getName().startsWith("db") && file.getName().endsWith("properties")) {
                Properties properties = ConfigImport.loadProp(file);
                String connConfigStr = properties.getProperty("channelId");
                if (StringUtils.isNullOrEmpty(connConfigStr)) {
                    System.out.println("找不到渠道id配置");
                    return;
                }
                channelId = Integer.parseInt(connConfigStr);
            }

        }

        String xmlPath = dirPath + "excelDir" + File.separator;

        List<String> mgrSortList = getMgrSortList();

        // 初始化映射表
        ExcelTableMapper.initMapper(xmlPath + "MappingConfig.xml");

        Map<String, String> fileMgrClassMapperMap = ExcelTableMapper.getFileMgrClassMapperMap();

        Set<String> allMgrStrSet = new HashSet<>();
        for (String excelName : excelNames) {
            String mgrName = fileMgrClassMapperMap.get(excelName);
            if (mgrName == null) {
                System.out.println(excelName + "找不到对应文件的Mgr类");
                continue;
            }
            List<String> strings = StringUtils.stringToStringList(mgrName, ",");
            allMgrStrSet.addAll(strings);
        }

        String mgrNames = "";
        for (String mgrName : mgrSortList) {
            if (allMgrStrSet.contains(mgrName)) {
                mgrNames += mgrName + ",";
            }
        }
        mgrNames = mgrNames.substring(0, mgrNames.length() - 1);

        //组装sql
        StringBuilder sb = new StringBuilder();
        sb.append("REPLACE INTO `t_s_config_version_check` (`channelId`,`mgrNames`,`configVersion`)values(" + channelId + ",\"" + mgrNames + "\",\"" + version + "\");");

        System.out.println(sb.toString());


        // 获取数据库连接,链接中心库
        Connection conn = initConn(configPath);
        if (conn == null) {
            throw new RuntimeException("数据库连接失败");
        }

        PreparedStatement ps = null;
        try {
            String sql = "REPLACE INTO `t_s_config_version_check` (`channelId`,`mgrNames`,`configVersion`)values(?,?,?)";
            ps = conn.prepareStatement(sql);
            ps.setInt(1, channelId);
            ps.setString(2, mgrNames);
            ps.setString(3, version);

            int ret = ps.executeUpdate();

            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        try {
            conn.commit();
            conn.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    public static List<String> getMgrSortList() {
        List<String> mgrList = new ArrayList<>();
        mgrList.add("MultipleLanguageMgr");
        mgrList.add("TitleMgr");
        mgrList.add("GoodsMgr");
        mgrList.add("GoodsBagMgr");
        mgrList.add("TempGoodsBagMgr");
        mgrList.add("BuildingMgr");
        mgrList.add("TaskMgr");
        mgrList.add("OldTaskChangeMgr");
        mgrList.add("MallMgr");
        mgrList.add("MallRechargeConfigMgr");
        mgrList.add("VipMgr");
        mgrList.add("NameMgr");
        mgrList.add("SystemOpenMgr");
        mgrList.add("ChildMgr");
        mgrList.add("BeautyMgr");
        mgrList.add("SkillMgr");
        mgrList.add("PatronsMgr");
        mgrList.add("VehicleMgr");
        mgrList.add("DecorationMgr");
        mgrList.add("LocationMgr");
        mgrList.add("TradeWarConfigMgr");
        mgrList.add("TravelMgr");
        mgrList.add("EstateWarConfigMgr");
        mgrList.add("HouseMgr");
        mgrList.add("UnionConfigMgr");
        mgrList.add("ZsConfigMgr");
        mgrList.add("HuntConfigMgr");
        mgrList.add("SacrificeConfigMgr");
        mgrList.add("BanquetConfigMgr");
        mgrList.add("BeautyEscortConfigMgr");
        mgrList.add("MammonConfigMgr");
        mgrList.add("SkinMgr");
        mgrList.add("CharitableWorkMgr");
        mgrList.add("MatchMgr");
        mgrList.add("PromotionMgr");
        mgrList.add("GrandChildConfigMgr");
        mgrList.add("CricketMgr");
        mgrList.add("ChatConfigMgr");
        mgrList.add("CurioConfigMgr");
        mgrList.add("DishesMgr");
        mgrList.add("ThiefMgr");
        mgrList.add("DrugStoreConfigMgr");
        mgrList.add("PassRoadMgr");
        mgrList.add("NpcConfigMgr");
        mgrList.add("ClinicMgr");
        mgrList.add("SkinVolumeMgr");
        mgrList.add("ManorMgr");
        mgrList.add("WineShopMgr");
        mgrList.add("FishPondMgr");
        mgrList.add("WingRoomConfigMgr");
        mgrList.add("WineryConfigMgr");
        mgrList.add("BadgeConfigMgr");
        mgrList.add("SmallGameConfigMgr");
        mgrList.add("MusicRoomConfigMgr");
        mgrList.add("VerificationConfigMgr");
        mgrList.add("KowloonMgr");
        mgrList.add("CrossBanquetConfigMgr");
        mgrList.add("CrossMatchConfigMgr");
        mgrList.add("KuangMgr");
        mgrList.add("CrossUnionHuaBenConfigMgr");
        mgrList.add("CrossUnionConfigMgr");
        mgrList.add("ConfigMgr");

        return mgrList;
    }

    static Connection initConn(String configPath) {
        File pathFile = new File(configPath);
        for (File file : pathFile.listFiles()) {
            if (file.getName().startsWith("db") && file.getName().endsWith("properties")) {
                Properties properties = ConfigImport.loadProp(file);
                String connConfigStr = properties.getProperty("db_road_servercenter.url");
                return ConfigImport.parseDbConfig(connConfigStr);
            }

        }
        return null;
    }
}
